﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;
using UnityEngine.UI;

namespace Nirvana
{
    /// <summary>
    /// 用于toggle控制动画机的动画状态切换
    /// </summary>
    [AddComponentMenu("Nirvana/UI/Control/Toggle Animator")]
    [RequireComponent(typeof(Toggle))]
    public sealed class ToggleAnimator : MonoBehaviour
    {
        [SerializeField]
        private Animator animator;
        [SerializeField]
        private string stateName;
        private Toggle _toggle;

        private void Awake()
        {
            this._toggle = base.GetComponent<Toggle>();
            Assert.IsNotNull<Toggle>(this._toggle);
            this.OnValueChanged(this._toggle.isOn);
            this._toggle.onValueChanged.AddListener(OnValueChanged);
        }

        private void OnEnable()
        {
            this.OnValueChanged(this._toggle.isOn);
        }

        private void OnValueChanged(bool IsOn)
        {
            if (this.animator.isInitialized && this.animator.isActiveAndEnabled)
            {
                this.animator.SetBool(this.stateName, IsOn);
            }
            else if (base.isActiveAndEnabled)
            {
                base.StopAllCoroutines();
                base.StartCoroutine(this.WaitStart());
            }
        }
        private IEnumerator WaitStart()
        {
            yield return new WaitUntil(()=> {
                if (this.animator.isInitialized && this.animator.isActiveAndEnabled)
                    return true;
                else
                    return false;

            });
            this.animator.SetBool(this.stateName, this._toggle.isOn);
            yield break;
        }

    }
}

